package lwk.juc.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author:lwk
 * @create: 2022-08-16 20:40
 * @Description: 读写锁
 *
 * 独占锁（写锁）：一次只能被一个线程占有
 * 共享锁（读锁）：多个线程可以同时占有
 *
 * 读锁和读锁：可以共存
 * 读锁和写锁：不可共存
 * 写锁和写锁：不可共存
 *
 */
public class ReadWriteLockDemo {


    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()-> {
                try {
                    myCache.put(String.valueOf(finalI), finalI);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()-> System.out.println(myCache.get(String.valueOf(finalI))),String.valueOf(i)).start();
        }
    }

}


class MyCache {


    private final Map<String,Object> map = new HashMap<>();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    //  存写
    public void put(String key,Object value) throws InterruptedException {

        lock.writeLock().lock();

        //TimeUnit.SECONDS.sleep(1);

        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入"+key+"完成");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.writeLock().unlock();
        }

    }

    //  读取
    public Object get(String key) {

        lock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取"+key+"完成");
            return o;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.readLock().unlock();
        }

    }

}